package com.wm.gridimageupload.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PointF
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View

class RoundProgress : View {

    private lateinit var mPaint: Paint
    private var color = Color.WHITE
    private val boundWidth = 2
    private var radius = 0
    private lateinit var center: PointF
    private var max = 0
    private var progress = 0f
    private lateinit var rect: RectF
    private var backgoundColor = 0

    constructor(context: Context?): this(context,null)

    constructor(context: Context?, attrs: AttributeSet?):this(context,attrs,0)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int):super(context, attrs, defStyleAttr) {
        if (context != null) {
            if (attrs != null) {
                initView(context, attrs, defStyleAttr)
            }
        }
    }

    private fun initView(context: Context, attrs: AttributeSet, defStyleAttr: Int) {
        max = 100
        progress = 1f
        backgoundColor = Color.parseColor("#b2000000")
        mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        color = Color.WHITE
        mPaint.color = color
        mPaint.strokeWidth = boundWidth.toFloat()
        center = PointF()
        rect = RectF()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        radius = w / (2 * 3)
        center.x = (w / 2).toFloat()
        center.y = (h / 2).toFloat()
        rect.left = center.x - radius
        rect.top = center.y - radius
        rect.right = center.x + radius
        rect.bottom = center.y + radius
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        mPaint.color = color
        mPaint.style = Paint.Style.STROKE
        canvas.drawCircle(center.x, center.y, radius.toFloat(), mPaint)
        val p = progress * 360.0f / max
        mPaint.style = Paint.Style.FILL
        canvas.drawArc(rect, -90f, p, true, mPaint)
    }

    fun setMax(max: Int) {
        this.max = max
    }

    fun setProgress(progress: Float) {
        this.progress = if (progress > max) max.toFloat() else (if (progress < 0) 0 else progress) as Float
        postInvalidate()
    }

}